package com.xw.service.impl;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xw.converter.WxUserJson2WxUserDTO;
import com.xw.dto.WxUserDTO;
import com.xw.entity.Users;
import com.xw.mapper.UsersMapper;
import com.xw.service.WeChatMsgHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;

import javax.annotation.Resource;
import javax.xml.xpath.XPathConstants;
import java.time.LocalDateTime;

/**
 * @Description:
 * @Author: y
 * @CreateDate: 9/15/21 11:02 AM
 * @Version: 1.0
 */
@Slf4j
@Service
public class WeChatMsgHandlerServiceImpl implements WeChatMsgHandlerService {


    @Resource
    private UsersMapper usersMapper;


    @Value("${wechat.mpAppId}")
    private String appId;

    @Value("${wechat.mpAppSecret}")
    private String secret;

    @Override
    public String handleMessage(String postData) {
        System.out.println(postData);
        // 提取密文
        Document document = XmlUtil.parseXml(postData);

        //MsgType
        String msgType = (String) XmlUtil.getByXPath("//MsgType", document, XPathConstants.STRING);

        switch (msgType) {
            case "text":
                return handleText(document);
            case "event":
                return handleEvent(document);
            default:
                break;
        }


        return null;

    }

    private String handleEvent(Document document) {
        //开发者微信号 //openid
        String userName = (String) XmlUtil.getByXPath("//FromUserName", document, XPathConstants.STRING);
        //接收方帐号（收到的OpenID） //帐号
        String openId = (String) XmlUtil.getByXPath("//ToUserName", document, XPathConstants.STRING);
        //CreateTime
        String createTime = (String) XmlUtil.getByXPath("//CreateTime", document, XPathConstants.STRING);
        //Content
        String content = (String) XmlUtil.getByXPath("//Content", document, XPathConstants.STRING);
        //EventKey
        String eventKey = (String) XmlUtil.getByXPath("//EventKey", document, XPathConstants.STRING);


        String template = "<xml>" +
                "  <ToUserName><![CDATA[" + userName + "]]></ToUserName>" +
                "  <FromUserName><![CDATA[" + openId + "]]></FromUserName>" +
                "  <CreateTime>" + createTime + "</CreateTime>" +
                "  <MsgType><![CDATA[text]]></MsgType>" +
                "  <Content><![CDATA[%s]]></Content>" +
                "</xml>";

        //门票预定
        if ("KEY_ZXYD_MPYD".equals(eventKey)) {

            regUser(userName);

            return String.format(template, "<a href=\"http://shuoxihu.0561cc.com?openId=" + userName + "\">点击这里门票预定～</a>");

        } else if ("KEY_ZXYD_LXWM".equals(eventKey)) {
            return String.format(template, "0561-3028668");
        } else {
            return String.format(template, "内容正在准备中~");
        }

    }

    private void regUser(String openId) {

        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        String response = restTemplate.getForObject(url, String.class);
        JSON parse = JSONUtil.parse(response);
        String accessToken = parse.getByPath("access_token").toString();
        String wxUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String wxUserInfo = restTemplate.getForObject(wxUserInfoUrl, String.class);
        WxUserDTO convert = WxUserJson2WxUserDTO.convert(wxUserInfo);

        Users u = new Users();
        u.setNickname(convert.getNickname());
        u.setCity(convert.getCity());
        u.setCreateTime(LocalDateTime.now());
        u.setGender(convert.getSex());
        u.setOpenid(convert.getOpenid());
        u.setAvatar(convert.getHeadimgurl());

        Users user = usersMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getOpenid, openId));

        if (user != null) {
            if (!u.getNickname().equals(user.getNickname())) {
                user.setNickname(convert.getNickname());
                user.setCity(convert.getCity());
                user.setCreateTime(LocalDateTime.now());
                user.setGender(convert.getSex());
                user.setOpenid(convert.getOpenid());
                user.setAvatar(convert.getHeadimgurl());

                usersMapper.updateById(user);
            }
        } else {
            usersMapper.insert(u);
        }

    }

    private String handleText(Document document) {

        //开发者微信号
        String userName = (String) XmlUtil.getByXPath("//FromUserName", document, XPathConstants.STRING);
        //接收方帐号（收到的OpenID）
        String openId = (String) XmlUtil.getByXPath("//ToUserName", document, XPathConstants.STRING);
        //CreateTime
        String createTime = (String) XmlUtil.getByXPath("//CreateTime", document, XPathConstants.STRING);

        String msg = "<xml>" +
                "  <ToUserName><![CDATA[" + userName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + openId + "]]></FromUserName>\n" +
                "  <CreateTime>" + createTime + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[感谢关注，更多功能尽请期待。。。]]></Content>\n" +
                "</xml>";
        return msg;

    }
}
